package com.hanlink.dsp;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Build;
import android.os.Bundle;
import android.os.Process;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.blankj.utilcode.util.AppUtils;
import com.hanlink.dsp.ui.widget.chart.EqGridView;
import com.hanlink.dsp.util.Constants;
import com.hanlink.dsp.util.DataUtil;
import com.inuker.bluetooth.library.BluetoothContext;
import com.qztech.bluetooth.BluetoothClientManager;
import com.qztech.sdk.BaseApplication;
import com.qztech.sdk.model.SettingConstants;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.File;
import java.io.PrintStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by PeterVon on 2015/9/20.
 */
public class BtDspApplication extends BaseApplication {

    private ActivityLifecycleCallbacks mActivityLifecycleCallbacks;
    private List<Activity>  mActivities;
    static {
        Constants.MAX_VOL = 20;
        DspSettings.FRENCY_LENGTH = 31;
        SettingConstants.GAIN_MAX = 200;
        SettingConstants.GAIN_MIN = -200;
        SettingConstants.GAIN_OFFSET = SettingConstants.GAIN_CENTER + SettingConstants.GAIN_MIN;
        SettingConstants.Q = 720F;
        EqGridView.griddB = new String[]{"20", "15", "10", "5", "0dB", "-5", "-10", "-15", "-20"};
        EqGridView.TEXT_SIZE = 20.0F;
        EqGridView.EQ_TIMES_CAL_P = -0.3555556F;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        mActivities = new LinkedList<>();
        BluetoothContext.set(this);
        DspContext.init(this);
        DataUtil.initDefaultUserProfile();
        CrashReport.initCrashReport(getApplicationContext());
//        Thread.setDefaultUncaughtExceptionHandler((t, e) -> {
//            restoreCrash(t, e);
//            killProcess();
//        });
        mActivityLifecycleCallbacks = new ActivityLifecycleCallbacks() {
            @Override
            public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
                mActivities.add(activity);
            }
            @Override
            public void onActivityDestroyed(@NonNull Activity activity) {
                mActivities.remove(activity);
                if (mActivities.isEmpty()){
                    if (BluetoothClientManager.getInstance(BtDspApplication.this).isConnect()) {
                        BluetoothClientManager.getInstance(BtDspApplication.this).disconnect();
                    }
                }
            }
            @Override
            public void onActivityStarted(@NonNull Activity activity) {

            }

            @Override
            public void onActivityResumed(@NonNull Activity activity) {

            }

            @Override
            public void onActivityPaused(@NonNull Activity activity) {

            }

            @Override
            public void onActivityStopped(@NonNull Activity activity) {

            }

            @Override
            public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

            }
        };
        registerActivityLifecycleCallbacks(mActivityLifecycleCallbacks);
    }

    private void killProcess() {
        Process.killProcess(Process.myPid());
    }

    @Override
    public void onTerminate() {
        super.onTerminate();
    }

    private void restoreCrash(@SuppressWarnings("unused") Thread thread, Throwable ex) {
        ex.printStackTrace(System.err);
        // 收集异常信息，写入到sd卡
        File dir = new File(getExternalFilesDir(null) + File.separator + "crash");

        if (!dir.exists()) {
            boolean mkdirs = dir.mkdirs();
            if (!mkdirs) {
                Log.e("bt", "CrashHandler create dir fail");
                return;
            }
        }

        try {
            @SuppressLint("SimpleDateFormat")
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String name = dateFormat.format(new Date(System.currentTimeMillis())) + ".log";
            File fileName = new File(dir, name);
            if (!fileName.exists()) {
                @SuppressWarnings("unused")
                boolean newFile = fileName.createNewFile();
            }

            PrintStream err = new PrintStream(fileName);

            err.println("--------------------------------AppInfo--------------------------------");
            err.println("AndroidVersion: " + AppUtils.getAppVersionName());
            err.println("--------------------------------SystemInfo:--------------------------------");
            err.println("Product: " + android.os.Build.PRODUCT);
            err.println("CPU_ABI: " + android.os.Build.CPU_ABI);
            err.println("TAGS: " + android.os.Build.TAGS);
            err.println("VERSION_CODES.BASE:" + android.os.Build.VERSION_CODES.BASE);
            err.println("MODEL: " + android.os.Build.MODEL);
            err.println("SDK: " + Build.VERSION.SDK_INT);
            err.println("VERSION.RELEASE: " + android.os.Build.VERSION.RELEASE);
            err.println("DEVICE: " + android.os.Build.DEVICE);
            err.println("DISPLAY: " + android.os.Build.DISPLAY);
            err.println("BRAND: " + android.os.Build.BRAND);
            err.println("BOARD: " + android.os.Build.BOARD);
            err.println("FINGERPRINT: " + android.os.Build.FINGERPRINT);
            err.println("ID: " + android.os.Build.ID);
            err.println("MANUFACTURER: " + android.os.Build.MANUFACTURER);
            err.println("USER: " + android.os.Build.USER);
            err.println();
            err.println();
            err.println("--------------------------------CrashContent--------------------------------");
            ex.printStackTrace(err);
            err.println();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
